package com.srb.sms.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.srb.sms.service.SmsService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author 宋伟宁
 * @Date 2024/1/5
 * @Version 1.0
 **/
@Service
public class SmsServiceImpl implements SmsService {

    @Value("${sms.accessKey}")
    private String accessKey;

    @Value("${sms.secretKey}")
    private String secretKey;

    @Value("${sms.signName}")
    private String signName;

    @Value("${sms.templateCode}")
    private String templateCode;

    @Override
    public boolean send(String phone, Map<String, Object> map) {
        DefaultProfile profile = DefaultProfile.getProfile("default", this.accessKey,this.secretKey);
        //发起 客户端
        IAcsClient client = new DefaultAcsClient(profile);
        //设置短信发送的信息 签名 手机号码 验证码
        CommonRequest request=new CommonRequest();
        //设置请求方式
        request.setSysMethod(MethodType.POST);
        //设置阿里云节点
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        //设置手机号码 设置成自己的
        request.putQueryParameter("PhoneNumbers",phone);
        //设置签名
        request.putQueryParameter("SignName",this.signName);
        //设置模板
        request.putQueryParameter("TemplateCode",this.templateCode);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));

        try {
            CommonResponse response=client.getCommonResponse(request);
            System.out.println(response);
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        return false;
    }
}
